package com.zmm.util.config;

import com.zmm.util.redis.RedisUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

/**
 * @author 900045
 * @description:
 * @name BaseConfigure
 * @date By 2021-06-22 14:52:39
 */
@Component
public class BaseConfigure {
	
	@Value("${spring.redis.database}")
	private Integer database;

	@Bean
	public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {

		/**
		 if (!(redisConnectionFactory instanceof LettuceConnectionFactory)) {
		 throw new RuntimeException(
		 "un_support redis connection factory! " + redisConnectionFactory);
		 }
		 */
		LettuceConnectionFactory lettuceConnectionFactory = (LettuceConnectionFactory) redisConnectionFactory;
		//  2.0.0配置方式，  2.1.7 之后无效了
		// lettuceConnectionFactory.setDatabase(database)
		// redisTemplate.setConnectionFactory(lettuceConnectionFactory)

		//2.1.7
		//可以直接用  spring.redis.database=6 配置

		//2.1.7之后要完全替换
		RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(
				lettuceConnectionFactory.getHostName(), lettuceConnectionFactory.getPort());
		redisStandaloneConfiguration.setDatabase(database);
		redisStandaloneConfiguration.setPassword(lettuceConnectionFactory.getPassword());
		LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory(
				redisStandaloneConfiguration, lettuceConnectionFactory.getClientConfiguration());
		//这句一定不能少
		connectionFactory.afterPropertiesSet();

		RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
		//FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class)
		//  使用JSON格式的序列化,保存
		redisTemplate.setKeySerializer(new StringRedisSerializer());
		redisTemplate.setHashKeySerializer(new StringRedisSerializer());
		// 值 不乱码
		redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
		redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
		redisTemplate.setConnectionFactory(connectionFactory);
		return redisTemplate;

	}

	@Bean
	public RedisUtil<Object> redisUtil(RedisTemplate<String, Object> redisTemplate) {
		return new RedisUtil<>(redisTemplate);
	}
}
